//
//  UserAcount.swift
//  新浪微博
//
//  Created by yaozhen on 2017/12/12.
//  Copyright © 2017年 ZYZ. All rights reserved.
//

import UIKit

private let accountFile : NSString = "useracount.json"

//用户账户信息
class UserAcount: NSObject {
    //访问令牌
    @objc var access_token: String?
    //用户代号
    @objc var uid : String?
    //过期日期： access_token声明周期 单位是秒
    //开发者5年 使用者三天
    @objc var expires_in : TimeInterval = 0 {
        didSet {
            expiresDate = Date.init(timeIntervalSinceNow: expires_in)
        }
    }
    
    //过期时间
    @objc var expiresDate: Date?
    
    
    @objc override var description: String{
        return yy_modelDescription()
    }
    override init() {
        super.init()
        //从磁盘加载保存的文件 -->字典
       guard let path  =  accountFile.cz_appendDocumentDir(),
        let data = NSData.init(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String : AnyObject]
        else{
            return
        }
//        let dict = JSONSerialization.jsonObject(with: data as Data, options: [])
        //使用字典设置属性值
        yy_modelSet(with: dict ?? [:])
        print("从本地加载数据\(self)")
        //判断token
//        expiresDate = NSDate.init(timeIntervalSinceNow: -3600*24) as Date
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("----账户过期")
            //清空tokenpa
            access_token = nil
            uid = nil
            //删除账户文件
          try? FileManager.default.removeItem(atPath: path)
            
        }
        print("----账户正常")
    }
    
    
    
    /*
     1 偏好设置 xocde 8bate无效
     2 沙河路径归档/plist/json
     3 数据库（FMDB/coreData)
     4 钥匙串访问（自动加密 需要使用框架）
     
     */
    func saveAcount(){
        //1  字典转模型
        // 需要删除expires_in值
        var dict = self.yy_modelToJSONObject() as?[String:AnyObject]
        dict?.removeValue(forKey: "expires_in")
        guard let data = try? JSONSerialization.data(withJSONObject: dict as Any, options: []),
        let fileName = (accountFile).cz_appendDocumentDir()
            else{
            return
        }
        (data as NSData).write(toFile: fileName, atomically: true)
        print("用户账户保存成功")
    }
}
